<?php
declare (strict_types=1);

namespace app\controller\admin;

use app\model\CheckType as CheckTypeModel;
use app\model\Railway as RailwayModel;
use app\model\RailwayStation as RailwayStationModel;
use app\model\CheckRecord as CheckRecordModel;
use app\model\CheckItem as CheckItemModel;
use app\model\User as UserModel;
use app\util\ReturnCode;
use think\facade\Db;

class Railway extends Base
{
    public function getRecord()
    {
        $model = new \app\model\Railway();
        $id = $this->request->get('id');
        $where = [
            ['id','=',$id]
        ];
        $railway = RailwayModel::where($where)
            ->with(['station'])
            ->find()
            ->toArray();
            
        $checkItemModel = new \app\model\CheckItem();
        
        // 获取用户名称映射
        $user_names = UserModel::column('name','id');
        
        // 获取封锁状态
        $blockade_status = [];
        foreach ($railway['station'] as $item) {
            $blockade_status[] = $item['status'];
        }
        
        // 构建表格数据
        $tableData = [
            [
                'type' => '封锁情况',
                'status' => $blockade_status,
            ]
        ];
        
        // 获取所有检查项目
        $checkItems = $checkItemModel->where([
            ['railway_id', '=', $id],
            ['delete_time', '=', null]
        ])
        ->field('id, type,railway_station_id, type_name, user_id, train_no, station_time, boarding_time, departure_time, arrival_time, complete_time, start_id, end_id, status')
        ->order('create_time', 'desc')
        ->select()
        ->toArray();
        
        // 调试输出
        \think\facade\Log::error("Check Items: " . json_encode($checkItems));
        
        // 按类型分组处理检查项目
        $typeGroups = [];
        foreach ($checkItems as $item) {
            $typeKey = $item['type'] . '_' . $item['type_name'];
            if (!isset($typeGroups[$typeKey])) {
                $typeGroups[$typeKey] = [
                    'name' => $item['type_name'],
                    'type' => $item['type'],
                    'items' => []
                ];
            }
            $typeGroups[$typeKey]['items'][] = $item;
        }
        
        // 调试输出
        \think\facade\Log::error("Type Groups: " . json_encode($typeGroups));
        
        // 处理每种类型的检查项目
        foreach ($typeGroups as $group) {
            $texts = [];
            $status_arr = [];
            $direction_arr = [];
            $type_arr = [];
            
            foreach ($railway['station'] as $station) {
                $text = '';
                $status = 1;
                $direction = 1;
                $type_id = 0;
                // 查找该站点的检查记录
                $record = null;
                foreach ($group['items'] as $item) {
                    // 如果是普通检查（type=2）
                    if ($item['type'] == 2) {
                        // 如果有station_time，就认为是该站点的记录
                        // if ($item['station_time']) {
                        //     $record = $item;
                        //     break;
                        // }
                        // 如果有start_id匹配，也认为是该站点的记录
                        if ($item['railway_station_id'] == $station['id']) {
                            $record = $item;
                            break;
                        }
                    }
                    // 如果是添乘检查（type=1）
                    if ($item['type'] == 1) {
                        // 如果有boarding_time，就认为是该站点的记录
                        // if ($item['boarding_time']) {
                        //     $record = $item;
                        //     break;
                        // }
                        // 如果有start_id匹配，也认为是该站点的记录
                        if ($item['railway_station_id'] == $station['id']) {
                            $record = $item;
                            break;
                        }
                    }
                }
                
                if ($record) {
                    $type_id = $record['type'];
                    $direction = 1; // 默认方向
                    
                    // 构建文本信息
                    $text = $record['train_no'] ? $record['train_no'] . ' ' : '';
                    $text .= $user_names[$record['user_id']] ?? '';
                    
                    if ($record['station_time']) {
                        $text .= date('h:i', $record['station_time']) . "到站，\n";
                    }
                    if ($record['boarding_time']) {
                        $text .= date('h:i', $record['boarding_time']) . "上车，\n";
                    }
                    if ($record['departure_time']) {
                        $text .= date('h:i', $record['departure_time']) . "开车";
                    }
                    
                    // 设置状态
                    if ($record['status'] == 2) {
                        $status = 2; // 完成
                    } elseif ($record['status'] == 1) {
                        $status = 3; // 进行中
                    }
                } else {
                    // 如果没有检查记录，但站点状态是封锁或检修，设置状态
                    if ($station['status'] > 1) {
                        $status = $station['status'];
                    }
                }
                
                // 调试输出
                \think\facade\Log::error("Station ID: " . $station['id'] . ", Text: " . $text . ", Status: " . $status);
                
                $texts[] = $text;
                $status_arr[] = $status;
                $direction_arr[] = $direction;
                $type_arr[] = $type_id;
            }
            
            $tableData[] = [
                'type' => $group['name'],
                'text' => $texts,
                'status' => $status_arr,
                'direction' => $direction_arr,
                'type_id' => $type_arr,
            ];
        }
        
        // 调试输出
        \think\facade\Log::error("Table Data: " . json_encode($tableData));
        
        $data = [
            'railway' => $railway,
            'tableData' => $tableData
        ];
        return $this->buildSuccess($data);
    }
    public function getRecord2()
    {
        $model = new \app\model\Railway();
        $id = $this->request->get('id');
        $where = [
            ['id','=',$id]
        ];
        $railway = $model->where($where)
            ->with(['station'])
            ->find()
            ->toArray();
        $typeModel = new CheckType();
        $recordModel = new \app\model\CheckRecord();
        $types = $typeModel->where(['status' => 1])->select()->toArray();
        $type_names = $typeModel->where(['status' => 1])->column('name','id');
        $columns = [
            [
                'title' => $railway['name'],
                'key' => 'type',
                'width' => 150,
                'align' =>'right'
            ],
            [
                'title' => ' ',
                'key' => 'dd',
                'width' => 80,
                'align' =>'center'
            ],
        ];
        foreach ($railway['station'] as $key => $station) {
            $columns[] = [
                'title' => $station['name'],
                'key' => 'station'.$key,
                'width' => 150,
                'align' =>'center'
            ];
            if($key < count($railway['station']) - 1){
                $columns[] = [
                    'title' => '······▶',
                    'key' => 'arrow'.$key,
                    'width' => 100,
                    'align' =>'center'
                ];
            }
        }
        $tableData = [
            [
                'type' => '封锁情况',
                'text' => [],
                'status' => [],
                'direction' => []
            ]
        ];
        $tableData[] = [
            'type' => '添乘检查',
            'text' => [],
            'status' => [],
            'direction' => []
        ];
        $data = [
            'columns' => $columns,
            'railway' => $railway,
            'tableData' => $tableData
        ];
        return $this->buildSuccess($data);
    }

    public function sort()
    {
        $railwayStationModel = new \app\model\RailwayStation();
        $id = $this->request->post('id',0);
        $station_ids = $this->request->post('station_ids',[]);
        if($station_ids){
            $station_ids = array_unique($station_ids);
            
            // 检查是否有封锁状态的站点
            $blockedStations = $railwayStationModel->where([
                ['railway_id', '=', $id],
                ['id', 'in', $station_ids],
                ['status', '=', 2]  // 2表示封锁状态
            ])->select();
            
            if (!empty($blockedStations)) {
                return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '存在封锁状态的站点，无法调整顺序');
            }
            
            foreach ($station_ids as $key => $station_id){
                $sort = $key + 1;
                $where = [
                    'railway_id' => $id,
                    'station_id' => $station_id,
                ];
                $railwayStationModel->where($where)->update(['sort' => $sort]);
            }
        }
        return $this->buildSuccess();
    }
    public function lists()
    {
        $model = new \app\model\Railway();
        $where = [];
        $status = $this->request->get('status',0);
        $keywords = $this->request->get('keywords','');
        $page = $this->request->get('page',1,'intval');
        $size = $this->request->get('size',10,'intval');
        if($status){
            $where[] = ['status','=',$status];
        }
        if($keywords){
            $where[] = ['name','like','%'.$keywords.'%'];
        }
        $count = $model->where($where)->count();
        $list = $model
            ->where($where)
            ->append(['station_ids'])
            ->order('id','desc')
            ->page($page,$size)
            ->select();
        $data = [
            'count' => $count,
            'list' => $list
        ];
        return $this->buildSuccess($data);
    }
    public function add()
    {
        $model = new \app\model\Railway();
        $stationModel = new \app\model\Station();
        $railwayStationModel = new \app\model\RailwayStation();
        $name = $this->request->post('name','');
        $station_ids = $this->request->post('station_ids',[]);
        $history = $model->where(['name' => $name])->find();
        if($history){
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR,'该铁路已存在：'.$name);
        }
        Db::startTrans();
        try {
            $data = [
                'name' => $name,
                'create_time' => time(),
            ];
            $id = $model->insertGetId($data);
            $arr = [];
            if($station_ids){
                $stations = $stationModel->column('name','id');
                foreach ($station_ids as $key => $station_id){
                    $arr[] = [
                        'railway_id' => $id,
                        'name' => $stations[$station_id] ?? '',
                        'station_id' => $station_id,
                        'sort' => $key+1,
                        'create_time' => time(),
                    ];
                }
                $railwayStationModel->insertAll($arr);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR,$e->getMessage());
        }
        return $this->buildSuccess();
    }
    public function edit()
    {
        $model = new \app\model\Railway();
        $stationModel = new \app\model\Station();
        $railwayStationModel = new \app\model\RailwayStation();
        $id = $this->request->post('id',0);
        $name = $this->request->post('name','');
        $station_ids = $this->request->post('station_ids',[]);

        // 确保station_ids是数组
        if (!is_array($station_ids)) {
            $station_ids = [];
        }

        // 检查是否存在封锁记录
        $checkRecord = \app\model\CheckRecord::where([
            ['railway_id', '=', $id],
            ['delete_time', '=', null],
            ['status', 'in', [0, 1, 2]]
        ])->find();

        if ($checkRecord) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '该铁路存在封锁记录，无法编辑');
        }

        // 获取当前铁路信息
        $currentRailway = $model->where('id', $id)->find();
        if (!$currentRailway) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND, '铁路不存在');
        }

        // 检查名称是否变更
        $nameChanged = $currentRailway['name'] !== $name;
        
        // 获取当前站点列表
        $currentStations = $railwayStationModel->where('railway_id', $id)
            ->order('sort', 'asc')
            ->select()
            ->toArray();
        
        // 检查站点是否变更
        $stationIdsChanged = false;
        if (count($currentStations) !== count($station_ids)) {
            $stationIdsChanged = true;
        } else {
            foreach ($currentStations as $index => $station) {
                if ($station['station_id'] != $station_ids[$index]) {
                    $stationIdsChanged = true;
                    break;
                }
            }
        }

        // 如果没有任何变更，直接返回成功
        if (!$nameChanged && !$stationIdsChanged) {
            return $this->buildSuccess();
        }

        $history = $model->where([['name','=',$name],['id','<>',$id]])->find();
        if($history){
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR,'该铁路已存在：'.$name);
        }
        Db::startTrans();
        try {
            $data = [
                'name' => $name
            ];
            if($id){
                $model->where(['id' => $id])->update($data);
            }else{
                $id = $model->insertGetId($data);
            }
            $arr = [];
            if($station_ids){
                $station_ids = array_unique($station_ids);
                $stations = $stationModel->column('name','id');
                foreach ($station_ids as $key => $station_id){
                    $arr[] = [
                        'railway_id' => $id,
                        'name' => $stations[$station_id] ?? '',
                        'station_id' => $station_id,
                        'sort' => $key+1,
                        'create_time' => time(),
                    ];
                }
                $railwayStationModel->where(['railway_id' => $id])->delete();
                $railwayStationModel->insertAll($arr);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR,$e->getMessage());
        }
        return $this->buildSuccess();
    }
    public function del()
    {
        $id = $this->request->get('id',0);
        if($id) {
            \app\model\Railway::destroy($id);
        }
        return $this->buildSuccess();
    }
    public function changeStatus()
    {
        $id = $this->request->get('id');
        $status = $this->request->get('status');
        $res = \app\model\Railway::update([
            'id'     => $id,
            'status' => $status
        ]);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR);
        }
        return $this->buildSuccess();
    }
    public function detail()
    {
        $id = $this->request->get('id');
        if (!$id) {
            return $this->buildFailed(ReturnCode::PARAM_INVALID);
        }

        $model = new \app\model\Railway();
        $data = $model->where('id', $id)->find();
        if (!$data) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND);
        }

        // 将对象转换为数组
        $data = $data->toArray();

        // 获取完整的铁路链
        $stations = \app\model\RailwayStation::alias('rs')
            ->join('station s', 's.id = rs.station_id')
            ->where('rs.railway_id', $id)
            ->field('rs.*, s.name, s.x, s.y')
            ->order('rs.sort', 'asc')
            ->select()
            ->toArray();

        // 获取所有状态的封锁记录
        $checkRecords = \app\model\CheckRecord::where([
            ['railway_id', '=', $id],
            ['delete_time', '=', null],
            ['status', 'in', [0, 1, 2]]  // 获取所有状态的记录
        ])->select()->toArray();

        // 为每个封锁区间分配颜色
        $colorIndex = 1;
        foreach ($checkRecords as $record) {
            // 获取区间内的所有站点
            $blockedStations = \app\model\RailwayStation::where([
                ['railway_id', '=', $id],
                ['id', '>=', $record['start_id']],
                ['id', '<=', $record['end_id']]
            ])->select()->toArray();

            // 标记区间内所有站点的颜色
            foreach ($blockedStations as $blockedStation) {
                foreach ($stations as &$station) {
                    if ($station['id'] == $blockedStation['id']) {
                        $station['block_group'] = $colorIndex;
                        break;
                    }
                }
            }
            $colorIndex++;
        }

        // 获取检查类型列表
        $checkTypes = \app\model\CheckType::where('status', 1)
            ->column('name', 'id');

        // 为每个站点添加检查项目
        foreach ($stations as &$station) {
            $station['check_item'] = [];
            if (!empty($station['check_item_ids'])) {
                $checkIds = explode(',', $station['check_item_ids']);
                foreach ($checkIds as $checkId) {
                    if (isset($checkTypes[$checkId])) {
                        $station['check_item'][] = $checkTypes[$checkId];
                    }
                }
            }
        }

        $data['station'] = $stations;
        return $this->buildSuccess($data);
    }
}
